package com.dw.controller;

import com.alibaba.fastjson.JSON;
import com.dw.entity.Department;
import com.dw.entity.User;
import com.dw.service.impl.DepServiceImpl;
import com.dw.service.impl.UserServiceImpl;
import com.dw.util.Md5Util;
import com.dw.util.RandomCode;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.security.provider.MD5;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @Description 用户核心控制器
 * @Author dw
 * @Date 2019/12/24 17:01
 * @Version 1.0
 **/
@Controller
@RequestMapping("/user")
public class UserController {


    /**
     * 返回到前端的数据集合
     **/
    Map<String,Object> resultMap;

    /**
     * 数据列名集合
     **/
    List<String> columnList;


    /**
     * 实体属性集合
     **/
    List<String> propertyList;

    /**
     * 条件集合
     **/
    Map<String,String> paramMap;

    /**
     * 用户服务层接口
     **/
    @Autowired
    private UserServiceImpl userService;

    /**
         部门服务
     */
    @Autowired
    private DepServiceImpl depService;
    /**
     * 登录方法
     *
     * @param user 用户实体对象
     * @return java.lang.Object
     */
    @RequestMapping("/login")
    @ResponseBody
    public Object login(User user, HttpServletRequest request,String vercode){
        //初始化
        paramMap = new HashMap<>();
        resultMap = new HashMap<>();
        HttpSession sessionCode = request.getSession();
        String code = (String)sessionCode.getAttribute(RandomCode.RANDOMCODEKEY);
        if(!code.equals(vercode.toUpperCase())){
            resultMap.put("msg","codeError");
            return JSON.toJSON(resultMap);
        }
        //添加第一个参数
        paramMap.put("columnOne","userId");
        paramMap.put("propertyOne",user.getUserId());
        //添加第二个参数
        paramMap.put("columnTwo","passWord");
        paramMap.put("propertyTwo", Md5Util.createMd5String(user.getPassWord()));
        User systemUser = userService.findByOne("user",paramMap);
        if(systemUser != null){
            //登录成功
            //将当前用户存储到session域中
            HttpSession session = request.getSession();
            //部门编号
            Integer depId = systemUser.getDepId();
            //查询编号所对应的部门信息
            paramMap = new HashMap<>();
            paramMap.put("columnOne","depId");
            paramMap.put("propertyOne",depId.toString());
            Department department = depService.findByOne("department",paramMap);
            //设置department
            systemUser.setDep(department);
            System.out.println(systemUser);
            session.setAttribute("user",systemUser);
            //判断是否为普通员工
            if(0 == systemUser.getAuthority()){
                resultMap.put("msg","0");
            }else{
                resultMap.put("msg","ok");
            }
        }else{
            //登录失败
            resultMap.put("msg","error");
        }
        return JSON.toJSON(resultMap);
    }


    /**
     * 登录成功跳转到首页
     *
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/goIndex")
    public String goIndex(){
        return "index";
    }

    /**
     * 跳转首页内容显示页面
     *
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/goHome")
    public String goHome(){
        return "home";
    }

    /**
     * 修改密码跳转
     *
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/updatePassword")
    public String updatePassword(){
        return "password";
    }

    /**
     * 验证老密码是否正确
     *
     * @param
     * @return java.lang.Object
     */
    @RequestMapping("/oldPasswordVerify")
    @ResponseBody
    public Object verifyOldPassword(String oldPassword,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        System.out.println(user.getPassWord());
        System.out.println(oldPassword);
        if(user.getPassWord().equals(Md5Util.createMd5String(oldPassword.replace("'","")))){
            //旧密码输入正确
            resultMap.put("msg","ok");
        }else{
            //旧密码输入错误
            resultMap.put("msg","error");
        }
        return JSON.toJSON(resultMap);
    }

    /**
     * 修改密码方法
     *
     * @param passWord 新密码
     * @return java.lang.Object
     */
    @RequestMapping("/goUpdatePassword")
    @ResponseBody
    public Object goUpdatePassword(String passWord,HttpSession session){
        columnList = new ArrayList<>();
        propertyList = new ArrayList<>();
        Map<String,String> idMap = new HashMap<>();
        columnList.add("passWord");
        propertyList.add(Md5Util.createMd5String(passWord));
        idMap.put("column","userId");
        User user = (User) session.getAttribute("user");
        idMap.put("property",user.getUserId());
        if(userService.update("user",columnList,propertyList,idMap) > 0){
            resultMap.put("msg","ok");
        }else{
            resultMap.put("msg","error");
        }
        return JSON.toJSON(resultMap);
    }

    /**
     * 个人信息页面跳转
     *
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/goInfo")
    public String goInfo(){
        return "info";
    }


    /**
     * 跳转到测评选择界面
     *
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/goVote")
    public String gogoVote(){
        return "vote";
    }

    /**
     * 跳转测评界面
     *
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/goVoteType")
    public String goDep(String voteType,String id,HttpSession session){
      if("员工".equals(voteType)){
         //查询员工信息
          paramMap = new HashMap<>();
          paramMap.put("columnOne","userId");
          paramMap.put("propertyOne",id);
          User emp = userService.findByOne("user",paramMap);
          session.setAttribute("emp",emp);
          return "emp";
      }else if("部门".equals(voteType)){
          //查询部门信息
          paramMap = new HashMap<>();
          paramMap.put("columnOne","depId");
          paramMap.put("propertyOne",id);
          Department dep = depService.findByOne("department",paramMap);
          session.setAttribute("dep",dep);
          return "dep";
      }else{
          return "others";
      }
    }

    /**
     * 跳转到重置密码提示页面
     *
     * @param
     * @return
     */
    @RequestMapping("/resetPassWord")
    public String resetPassWord(){
        return "reset_password";
    }

    /**
     * 更新用户信息
     *
     * @param
     * @return
     */
    @RequestMapping("/updateInfo")
    @ResponseBody
    public Object updateInfo(String userName,String userGender,String tel,HttpSession session){
        //初始化
        resultMap = new HashMap<>();
        columnList = new ArrayList<>();
        propertyList = new ArrayList<>();
        Map<String,String> idMap = new HashMap<>();
        //当前登录状态的用户
        User sysUser = (User)session.getAttribute("user");
        //添加第一个参数
        idMap.put("column","userId");
        idMap.put("property",sysUser.getUserId());
        System.out.println(idMap);
        System.out.println(sysUser.getUserId());
        //只有当数据不一致时在进行更新操作
        if(userName != null && !userName.equals("")){
            if(!userName.equals(sysUser.getUserName())){
                //不一致执行更新操作
                columnList.add("userName");
                propertyList.add(userName);
            }
        }
        if(userGender != null && !userGender.equals("")){
            if(!userGender.equals(sysUser.getUserGender())){
                //不一致执行更新操作
                columnList.add("userGender");
                propertyList.add(userGender);
            }
        }
        if(tel != null && !tel.equals("")){
            if(!tel.equals(sysUser.getTel())){
                //不一致执行更新操作
                columnList.add("tel");
                propertyList.add(tel);
            }
        }

        if(userService.update("user",columnList,propertyList,idMap) >0 ){
            //更新成功
            resultMap.put("msg","ok");
        }else{
            resultMap.put("msg","error");
        }
        return JSON.toJSON(resultMap);
    }



    /**
     * 检查账号是否存在
     *
     * @param userId
     *
     * @return
     */
    @RequestMapping("/userIdExist")
    @ResponseBody
    public Object idExist(String userId){
        //初始化
        paramMap = new HashMap<>();
        resultMap = new HashMap<>();
        resultMap = new HashMap<>();
        //学院管理员登录
        //添加第一个参数
        paramMap.put("columnOne","userId");
        paramMap.put("propertyOne",userId);

        User user = userService.findByOne("user",paramMap);
        if(user != null){
            //账号存在
            resultMap.put("msg","ok");
        }else{
            //账号不存在
            resultMap.put("msg","error");
        }
        return JSON.toJSON(resultMap);
    }


    /**
     * 跳转到用户列表页面
     *
     * @param
     * @return java.lang.String
     */
    @RequestMapping("goUserList")
    public String goUserList(){
        return "user_list";
    }


    /**
     * 加载所有学生信息
     *
     *
     *
     * @param userId
     * @param limit
     *
     * @param page
     * @return
     */
    @RequestMapping("/loadUserList")
    @ResponseBody
    public Object loadUserList(String userId, Integer page, Integer limit){
        paramMap = new HashMap<>();
        //只能查看审批通过的
        System.out.println("userId"+userId);
        paramMap.put("userId",userId);
        List<Map<Object,Object>> objects = userService.getPageList("user",(page-1)*limit,limit,paramMap);
        for (int i = 0; i < objects.size(); i++) {
            try {

                //查询部门名称
                Map<String,String> depParamMap = new HashMap<>();
                depParamMap.put("columnOne","depId");
                depParamMap.put("propertyOne",objects.get(i).get("depId").toString());
                Department dep = depService.findByOne("department",depParamMap);
                //添加college,并且将数据返回到前端页面
                objects.get(i).put("dep",dep);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Integer count = userService.getTotalCount("user");
        Map<String,Object> res = new HashMap<>();
        res.put("code",0);
        res.put("msg","");
        res.put("count",count);
        res.put("data",objects);
        return JSON.toJSON(res);
    }


    /**
     * 跳转到修改页面
     *
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/goUpdateUser")
    public String goUpdateUser(){
        return "updateUser";
    }

    /**
     * 跳转到添加用户界面
     *
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/goAddUser")
    public String goAddHouse(){
        return "addUser";
    }

    /**
     * 查询部门下的所有员工信息
     *
     * @param
     * @return
     */
    @RequestMapping("/loadAll")
    @ResponseBody
    public Object loadAll(String depId){
        paramMap = new HashMap<>();
        resultMap = new HashMap<>();
        paramMap.put("column","depId");
        paramMap.put("property",depId);
        List<User> userList = userService.findAll("user",paramMap);
        resultMap.put("userList",userList);
        return JSON.toJSON(userList);
    }

    /**
     * 用户信息更新
     *
     * @param
     * @return java.lang.Object
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public Object updateHouse(User user){
        List<String> columnList = new ArrayList<>();
        List<String> propertyList = new ArrayList<>();
        Map<String,String> idMap = new HashMap<>();
        resultMap = new HashMap<>();

        columnList.add("userName");
        columnList.add("userGender");
        columnList.add("depId");
        columnList.add("tel");

        propertyList.add(user.getUserName());
        propertyList.add(user.getUserGender());
        propertyList.add(user.getDepId().toString());
        propertyList.add(user.getTel());


        idMap.put("column","userId");
        idMap.put("property",user.getUserId().toString());

        if(userService.update("user",columnList,propertyList,idMap) > 0){
            resultMap.put("msg","ok");
        }
        else{
            resultMap.put("msg","error");
        }
        return JSON.toJSON(resultMap);
    }

    /**
     * 添加新员工
     *
     * @param user
     * @return java.lang.Object
     */
    @RequestMapping("/addUser")
    @ResponseBody
    public Object addHouse(User user){
        columnList = new ArrayList<>();
        propertyList = new ArrayList<>();
        resultMap = new HashMap<>();

        columnList.add("userId");
        columnList.add("userName");
        columnList.add("userGender");
        columnList.add("depId");
        columnList.add("passWord");
        columnList.add("authority");
        columnList.add("tel");

        propertyList.add(user.getUserId());
        propertyList.add(user.getUserName());
        propertyList.add(user.getUserGender());
        propertyList.add(user.getDepId().toString());
        propertyList.add(Md5Util.createMd5String(user.getPassWord()));
        propertyList.add(user.getAuthority().toString());
        propertyList.add(user.getTel());


        if(userService.insert("user",columnList,propertyList) > 0){
            resultMap.put("msg","ok");
        }else{
            resultMap.put("msg","error");
        }
        return JSON.toJSON(resultMap);
    }


    /**
     * 删除员工
     *
     * @param userId
     * @return java.lang.Object
     */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public Object delete(String userId){
        Map<String,String> idMap = new HashMap<>();
        resultMap = new HashMap<>();
        idMap.put("column","userId");
        idMap.put("property",userId.replace("'",""));
        if(userService.delete(idMap) > 0){
            resultMap.put("msg","ok");
        }else{
            resultMap.put("msg","error");
        }
        return JSON.toJSON(resultMap);
    }

    /**
     * 得到登陆验证码
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomCode randomCode = new RandomCode();
        try {
            randomCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
